﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication3
{
    public partial class NewUserForm : Form
    {
        private bool nonNumberEntered = false;
          private String connString = Program.ConnStr;
        public NewUserForm()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Normal;

        }
        /// <summary>
        /// when the add button clicked 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {

            try
            {

                if (validationcontrol())
                {
                    if (btnAdd.Text == "Add")
                    {
                        if (wheatheruseridpresent(txtuserId.Text) == false)
                        {
                            MessageBox.Show("Userid Exist enter another");
                            txtuserId.Text = "";
                            txtPassword.Text = "";
                            txtconfirmPassword.Text = "";
                            txtPhoneNo.Text = "";
                            rhtAdress.Text = "";
                        }
                        else
                        {
                            UserDataBean userdata = new UserDataBean();

                            userdata.Username = txtName.Text;
                            userdata.Userid = txtuserId.Text;
                            userdata.Passsword = txtPassword.Text;
                            userdata.Adress1 = rhtAdress.Text;
                            userdata.Phone = txtPhoneNo.Text;


                            if (userdata != null)
                            {
                                addaction(userdata);

                            }

                        }

                    }

                    else
                    {

                        UserDataBean userdata = new UserDataBean();

                        userdata.Username = txtName.Text;
                        userdata.Userid = txtuserId.Text;
                        userdata.Passsword = txtPassword.Text;
                        userdata.Adress1 = rhtAdress.Text;
                        userdata.Phone = txtPhoneNo.Text;


                        if (userdata != null)
                        {
                            updateuserdetails();

                            btnAdd.Text = "Add";
                            clearcontrol();
                        }

                    }

                }
                showdata12();

            }

            catch (Exception exp)
            {
                MessageBox.Show("The application had met with some errors please restart  the application :\n error:" + exp + "");

            }






        }

      
        
        
        /// <summary>
        /// 
        /// to show user Data from database
        /// </summary>
        public void showdata12()
        {
            try
            {
                //  String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Documents and Settings\\Adminstrator\\My Documents\\NauferTransactionDemoDB.accdb";

                //  String query = "Select  * from masterusertable ";
                String query = "Select username,userid,passsword,phoneno ,adress from masterusertable ";
                OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
                DataSet ds = new DataSet();
                dAdapter.Fill(ds, "tbluserdataview");
                tbluserview.DataSource = ds.Tables["tbluserdataview"].DefaultView;

            }
            catch (Exception exp)
            {
                MessageBox.Show("The application had met with some errors please restart  the application :\n error:closer MSAccess files");
                Console.WriteLine("Error", exp);
            }


        }





        /// <summary>
        /// when  page load
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void NewUserForm_Load(object sender, EventArgs e)
        {
            showdata12();
            txtName.Focus();
        }


        /// <summary>
        /// when cancel button clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Update")
            {
                btnAdd.Text = "Add";
                clearcontrol();
            }
            else
            {

                
                this.Close();
            }
        }

       
        
        
        
        /// <summary>
        /// to find whether userid is already present
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public Boolean wheatheruseridpresent(String userid)
        {

            Boolean idavailable = true;
            try
            {
                //  String s = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Documents and Settings\\Adminstrator\\My Documents\\NauferTransactionDemoDB.accdb";
                OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
                oleDbConnection1.Open();
                OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select * from masterusertable where userid='" + userid.ToString() + "'", oleDbConnection1);
                oleDbCommand1.CommandType = CommandType.Text;

                OleDbDataReader data = oleDbCommand1.ExecuteReader();

                if (data.Read() == true)
                {


                    idavailable = false;


                   
                }
               

            }
            catch (Exception exp)
            {
                MessageBox.Show("Exception at Database close any Access Database program and restart");
                Console.WriteLine("Error", exp);

            }

            return idavailable;
        }

      
        
        /// <summary>
        /// clear all the controls
        
        /// </summary>
        public void clearcontrol()
        {
            txtName.Text = "";
            txtPassword.Text = "";

            txtPhoneNo.Text = "";
            txtuserId.Text = "";
            txtconfirmPassword.Text = "";
            rhtAdress.Text = "";
            txtName.Focus();
            txtuserId.Enabled = true;

        }
        /// <summary>
        /// Validates every user Input
        /// </summary>
        /// <returns></returns>

        public Boolean validationcontrol()
        {
            Boolean sucess = false;
            if (txtName.Text.Trim() == null || txtName.Text.Trim() == "")
            {
                lblstatus.Text = "Enter Name";
                txtName.Focus();
                txtName.Text = "";
            }
            else if (txtuserId.Text.Trim() == null || txtuserId.Text.Trim() == "")
            {

                txtuserId.Focus();
                lblstatus.Text = "Enter an Userid";
                txtuserId.Text = "";
            }

            else if (txtPassword.Text.Trim() == null || txtPassword.Text.Trim() == "")
            {

                txtPassword.Focus();
                lblstatus.Text = "Enter an valid password";
                txtPassword.Text = "";
            }
            else if (txtconfirmPassword.Text.Trim() == null || txtconfirmPassword.Text.Trim() == "")
            {

                txtconfirmPassword.Focus();
                lblstatus.Text = "Confirm Password";
                txtconfirmPassword.Text = "";
            }
            else if (txtconfirmPassword.Text.Trim() != txtPassword.Text.Trim())
            {

                txtuserId.Focus();
                lblstatus.Text = "The Password And Confirm Password Doesnt Match";
                txtconfirmPassword.Text = "";
                txtPassword.Text = "";
            }
            else
            {

                sucess = true;
            }
            return sucess;
        }
        

        /// <summary>
        /// Add Data to Database
        /// 
        /// </summary>
        /// <param name="userdata"></param>
        public void addaction(UserDataBean userdata)
        {

            try
            {

                OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
                oleDbConnection1.Open();
                OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO masterusertable (username ,userid,passsword,phoneno,adress) Values ('" + userdata.Username + "', '" + userdata.Userid + "','" + userdata.Passsword + "','" + userdata.Phone + "'  ,'" + userdata.Adress1 + "') ", oleDbConnection1);
                oleDbCommand1.CommandType = CommandType.Text;
                oleDbCommand1.ExecuteNonQuery();

                oleDbConnection1.Close();
                showdata12();
                clearcontrol();

            }
            catch (Exception)
            {


            }





        }


        /// <summary>
        /// update usermastertable from data in usercontrols
        /// 
        /// </summary>


        public void updateuserdetails()
        {
            try
            {

                if (validationcontrol())
                {




                    UserDataBean userdata = new UserDataBean();


                    userdata.Username = txtName.Text;
                    userdata.Userid = txtuserId.Text;
                    userdata.Passsword = txtPassword.Text;
                    userdata.Adress1 = rhtAdress.Text;
                    userdata.Phone = txtPhoneNo.Text;


                    if (userdata != null)
                    {






                        try
                        {

                            OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
                            oleDbConnection1.Open();
                            String query = "Update masterusertable set username='" + userdata.Username + "',passsword='" + userdata.Passsword + "',phoneno='" + userdata.Phone + "', adress='" + userdata.Adress1 + "' where userid ='" + userdata.Userid + "'";


                            OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand(query, oleDbConnection1);
                            oleDbCommand1.CommandType = CommandType.Text;

                            oleDbCommand1.ExecuteNonQuery();

                            oleDbConnection1.Close();
                            showdata12();
                            clearcontrol();

                        }
                        catch (Exception exp)
                        {
                            MessageBox.Show("" + exp);

                        }









                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("The application had met with some errors please restart  the application :\n error:" + exp + "");

            }

        }

        private void txtPhoneNo_KeyPress(object sender, KeyPressEventArgs e)
        { // Check for the flag being set in the KeyDown event.
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
                lblstatus.Text = "Enter A Phone Number";

            }
            else
            {
                if (e.KeyChar == '\t')
                {
                    lblstatus.Text = "";
                    rhtAdress.Focus();
                }

            }

        }

        private void txtPhoneNo_KeyDown(object sender, KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace.
                    if (e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }

                }
            }
            //If shift key was pressed, it's not a number.
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;

            }

        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int rowno = tbluserview.CurrentCellAddress.Y;

            txtName.Text = tbluserview.Rows[rowno].Cells[0].Value.ToString();
            txtuserId.Text = tbluserview.Rows[rowno].Cells[1].Value.ToString();
            txtPassword.Text = tbluserview.Rows[rowno].Cells[2].Value.ToString();
            txtconfirmPassword.Text = tbluserview.Rows[rowno].Cells[2].Value.ToString();
            txtPhoneNo.Text = tbluserview.Rows[rowno].Cells[3].Value.ToString();
            rhtAdress.Text = tbluserview.Rows[rowno].Cells[4].Value.ToString();

            btnAdd.Text = "Update";
            txtuserId.Enabled = false;
             
         
        }

        


    }
}
